<!-- addPoster -->
<template>
  <div class="addPoster">
    <el-dialog
      :title="formName"
      :visible="dialogVisible"
      width="30%"
      @update:visible="updateShow"
      destroy-on-close
    >
      <div class="flex align-center m-b-1">
        <span class="spspan">海报类型：</span>
        <el-select
          v-if="formData.Id"
          v-model="formData.PosterType"
          placeholder="海报类型"
          @change="exitPosterType($event)"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.EnumName"
            :label="item.Desction"
            :value="item.EnumName"
          >
          </el-option>
        </el-select>

        <el-select v-else v-model="PosterType" placeholder="请选择" clearable>
          <el-option
            v-for="item in typeOptions"
            :key="item.EnumName"
            :label="item.Desction"
            :value="item.EnumName"
          >
          </el-option>
        </el-select>
      </div>

      <!-- 横幅选择框 -->
      <div v-if="PosterType == 'Banner' || formData.PosterType == 'Banner'" class="flex align-center m-b-1" >
        <span class="spspan">网址路径：</span>
        <el-autocomplete
          suffix-icon="el-icon-arrow-down"
          clearable
          class="title-box"
          v-model="state"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          @select="handleSelect"
        ></el-autocomplete>
        <div v-if="PosterType == 'Banner' || formData.PosterType == 'Banner'">
          <div v-if="state == '文章-pages/articlePage/articlePage'" class="flex align-center m-b-1">
            <el-select v-model="PcDataId" placeholder="请选择文章内容" clearable class="banner">
              <el-option
                v-for="item in options"
                :key="item.Id"
                :label="item.Subject"
                :value="item.Id">
              </el-option>
            </el-select>
          </div>
        </div>
        
        
      </div>
      


      <div v-if="formData.Id">
        <div v-if="formData.PosterType == 'Notice'">
          <span style="line-height: 20px">是否启用 </span>
          <el-switch v-model="formData.IsShow"></el-switch>
        </div>
          
      </div>
      <div v-else >
        <div v-if="PosterType == 'Notice' " style="margin-bottom: 10px">
          <span style="line-height: 20px">如需启用公告,请在上传后点击编辑进行更改 </span>
          <!-- <el-switch v-model="IsShow"></el-switch> -->
        </div>
      </div>
      <div v-if="formData.Id">
        <div class="flex align-center m-b-1" v-if="formData.PosterType == 'InviteMembers'">
          <span class="spspan">广告语：</span>
          <el-input v-model="formData.Slogan"  placeholder="请填写海报广告语" clearable></el-input>
        </div>
      </div>
      <div v-else>
        <div class="flex align-center m-b-1" v-if="PosterType == 'InviteMembers'">
          <span class="spspan">广告语：</span>
          <el-input v-model="Slogan"  placeholder="请填写海报广告语" clearable></el-input>
        </div>
      </div>

      <div class="picture-box" v-if="formData.Id">
        <div>
          <div class="title-box">原图片</div>
          <img :src="formData.Path" alt="">
        </div>
        <div>
          <div style="margin-left: 80px;" class="title-box">更改图片</div>
          <el-upload
            :action="upload"
            :headers="headerObj"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :before-upload="beforeUploadFun"
            :auto-upload="true"
            :on-success="upLoadSuccess"
            :limit="1"
            :on-remove="handleRemove"
            style="margin-left: 80px;"
          >
            <i class="el-icon-plus"></i>
          </el-upload> 
        </div>
      </div>
      <div v-else>
        <el-upload
          :action="upload"
          :headers="headerObj"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="beforeUploadFun"
          :auto-upload="true"
          :on-success="upLoadSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateShow(false)">取 消</el-button>
        <el-button v-if="formData.Id" type="primary" @click="exitSave(event, formData)">保 存</el-button>
        <el-button v-else type="primary" @click="saveFun">保 存</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible2" width="50%">
      <img style="width: 100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { GetUploadToken, Save } from '@/api/ShareSetting/poster'
import { getList } from '@/api/message.js'
export default {
  //import引入的组件需要注入到对象中才能使用
  name: 'addPoster',
  components: {},
  props: {
    formData: {
      type: Object,
      default: function () {
        return {}
      }
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    typeOptions: {
      type: Array,
      default: function () {
        return []
      }
    },
  },
  data () {
    //这里存放数据
    return {
      BannerPath: [],
      PcDataId: '',
      PcData: '',
      options: [],
      restaurants: [], // 横幅显示内容
      state: '', // 横幅绑定的内容
      newItem: {
        path: ''
      },
      tableData: [],
      loadAll: [
        { "value": "首页-pages/index/index", "path": "/pages/index/index" },
        { "value": "团队-pages/team/index", "path": "/pages/team/index" },
        { "value": "文章-pages/articlePage/articlePage", "path": "/pages/articlePage/articlePage" },
        { "value": "登录-pages/login/accountLogin", "path": "/pages/login/accountLogin" },
        { "value": "交易详情-pages/trade/detail", "path": "/pages/trade/detail" },
        { "value": "邀请与拓展-pages/expand/expand", "path": "/pages/expand/expand" },
        { "value": "活动进度-pages/activity/progress", "path": "/pages/activity/progress" },
        { "value": "会员升级-pages/user/memberUp", "path": "/pages/user/memberUp" },
        { "value": "排行榜-pages/rank/index", "path": "/pages/rank/index" },
        { "value": "用户信息登记-pages/user/updateInfo", "path": "/pages/user/updateInfo" },
        { "value": "分享-pages/share/share", "path": "/pages/share/share" },
        { "value": "收益-pages/income/index", "path": "/pages/income/index" },
        { "value": "收益明细-pages/income/searchDetail/standardSearch", "path": "/pages/income/searchDetail/standardSearch" },
        { "value": "交易查询-pages/trade/search", "path": "/pages/trade/search" },
        { "value": "提现流水-pages/income/cashFlow", "path": "/pages/income/cashFlow" },
        { "value": "提现-pages/income/withdraw", "path": "/pages/income/withdraw" },
        { "value": "服务商详情-pages/team/agent/detail", "path": "/pages/team/agent/detail" },
        { "value": "我的用户-pages/myUsers/myUsers", "path": "/pages/myUsers/myUsers" },
        { "value": "用户详情-pages/myUsers/detail/detail", "path": "/pages/myUsers/detail/detail" },
        { "value": "我的团队-pages/team/myTeam/myTeam", "path": "/pages/team/myTeam/myTeam" },
        { "value": "达标查询-pages/ploySearch/upStandard", "path": "/pages/ploySearch/upStandard" },
        { "value": "激活查询-pages/ploySearch/activation", "path": "/pages/ploySearch/activation" },
        { "value": "用户中心-pages/user/index", "path": "/pages/user/index" },
        { "value": "设置密码-pages/user/resetPassword", "path": "/pages/user/resetPassword" },
        { "value": "结算账户-pages/user/bankAccount", "path": "/pages/user/bankAccount" },
        { "value": "基本资料-pages/user/info", "path": "/pages/user/info" },
        { "value": "联系我们-pages/user/contactUs", "path": "/pages/user/contactUs" },
      ],

      IsShow: false,
      event: '',
      form: {},
      upload: process.env.VUE_APP_UPLOAD_API + '/api/Tools/UploadFiles',
      PosterType: "",
      headerObj: {
        Authorization: ''
      },
      successList: [],
      dialogVisible2: false,
      dialogImageUrl: "",
      Slogan:''
    };
  },
  //监听属性 类似于data概念
  computed: {
    formName (){
      if(this.formData.Id){
        this.PosterType = ''
        this.getArticleList()
        return '编辑海报'
      }
        this.PosterType = ''
        return '上传海报'
    }
  },
  //监控data中的数据变化
  watch: {
    formData: {
      deep: true,
      immediate: true,
      handler (val) {
        console.log('监听')
        console.log(val)
        if(val.PosterType == "userRights"){
          this.form = val
          if(this.BannerPath){
            this.deconstruct(this.form)
            console.log(1123)
          }
        }
        
      }
    }
  },
  //方法集合
  methods: {
    // 横幅 输入框方法
    querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        console.log(restaurants)
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      handleSelect(item) {
        this.newItem = item
      },



    exitPosterType (e){
      this.event = e
    },
    exitSave (e, item) {
      console.log(e, item)
      if ( e == '' ){
        e = this.formData.PosterType
      }
      if ( e != 'InviteMembers' ){
        this.formData.Slogan = null
      }
      if (this.successList.length != 0){
        item.Path = this.successList[0]
      }
      if (e != 'Notice'){
        console.log(123)
        item.IsShow = false
      }
      this.pathId()

      
      let obj = {
        "Id": item.Id,
        "PosterType": e,
        'Path': item.Path,
        "IsShow": item.IsShow,
        "BannerPath": this.PcData
      }
      if(this.formData.Slogan){
        let Slogan = this.formData.Slogan
         obj = {
          ...obj, Slogan
        }
        console.log(obj)
      }
      Save([obj]).then(res => {
        this.$notify({
          title: '修改成功',
          message: res.Msg,
          type: 'success',
          duration: 3000
        })
      }).catch(err => {
        this.$notify({
          // title: '修改失败',
          // message: res.Msg,
          // type: 'warning',
          // duration: 3000
        })
      })
      this.updateShow(false)
    },
    pathId (){
      if(this.PcDataId){
        return this.PcData = this.newItem.path + '?pcData=' + this.PcDataId 
      }

      for(let item of this.loadAll){
        if(this.state == item.value){
          return this.PcData = this.newItem.path
          
        }
      }
      
      
      // if(this.newItem.value == "文章-pages/articlePage/articlePage"){
      //    this.PcData = this.newItem.path + '?pcData=' + this.PcDataId 
      // }
      // if(this.newItem.value != "文章-pages/articlePage/articlePage"){
      //    this.PcData = this.newItem.path
      // }
      return this.PcData = this.state
    },
    // :show.sync="showForm"
    updateShow (val) {
      this.$emit('update:dialogVisible', val)
      this.successList=[]
      this.$parent.getListFun()
    },
    async saveFun () {
      let remsg = ''
      let ctr = false
      if (this.successList.length == 0) {
        remsg = '请上传图片'
        ctr = true
      }
      if (!this.PosterType) {
        remsg = '请选择本次上传的海报类型'
        ctr = true
      }
      if(this.PosterType == "InviteMembers" && !this.Slogan){
        remsg = '请填写广告语'
        ctr = true
      }
      if (ctr) {
        this.$notify({
          title: '提示',
          message: remsg,
          type: 'warning',
          duration: 2000
        })
        return
      }
      this.pathId()
      let templ = {
        "Id": "00000000-0000-0000-0000-000000000000",
        "PosterType": this.PosterType,
        "BannerPath": this.PcData
      }
      
      let slist = this.successList.map(item => {
        return { ...templ, Path: item ,Slogan:this.Slogan }
      })
      let { Data, Msg } = await Save(slist)
      this.$notify({
        title: '上传成功',
        message: Msg,
        type: 'success',
        duration: 3000
      })
      this.$parent.getListFun()
      this.updateShow(false)
    },
    handleRemove (file, fileList) {
      console.log(file)
      if(fileList.length == 0){
        return this.successList = []
      }
      console.log(fileList)
      for (let item of fileList){
        this.successList.push(item.response.data.fileUrl)
      }
    },
    handlePictureCardPreview (file) {
      //图片放大
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },
    async beforeUploadFun (e) {
      if (!this.headerObj.Authorization) {
        return false
      }
    },
    async GetUploadTokenFun () {
      let { Data } = await GetUploadToken()
      this.headerObj.Authorization = Data || ''
    },
    upLoadSuccess (res) {
      console.log('上传结束', res)
      if (res.code === 0) {
        this.successList.push(res.data.fileUrl)
      } else {
        if (this.sstimer) {
          clearTimeout(this.sstimer)
        }
        this.sstimer = setTimeout(() => {
          this.$notify({
            title: '上传失败',
            message: res.msg,
            type: 'warning',
            duration: 4500
          })
        }, 800)
      }
    },


    getArticleList () {
      this.options = []
      let obj = {
        "IsPaging": false, //是否分页
        "SortType": false,//排序类型｛True：正序；Flase：反序｝

      }
      getList(obj).then(res => {
        for(let item of res.Data){
          if(item.MessageType == "Article"){
            this.options.unshift(item)
          }
        }
      })
    },
    deconstruct ( res ){
      let BannerPath = res.BannerPath.split('?pcData=')
      this.newItem.path = BannerPath[0]
      this.PcDataId = BannerPath[1]
      for(let load of this.loadAll){
        if(load.path == this.newItem.path){
          this.state = load.value
          this.newItem.push(load.value)
          console.log(this.state)
        }
      }
      
    }

  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    
    if (!this.headerObj.Authorization) {
      this.GetUploadTokenFun()
    }
    this.form = this.formData
    
    console.log(this.form)
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.restaurants = this.loadAll;
  },
  beforeCreate () { }, //生命周期 - 创建之前
  beforeMount () { }, //生命周期 - 挂载之前
  beforeUpdate () { }, //生命周期 - 更新之前
  updated () { }, //生命周期 - 更新之后
  beforeDestroy () { }, //生命周期 - 销毁之前
  destroyed () { }, //生命周期 - 销毁完成
  activated () { }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
//@import url(); 引入公共css类
<style  scoped>
.spspan {
  white-space: nowrap;
  width: 75px;
  flex-shrink: 0;
}
.picture-box {
  margin-top: 15px;
  display: flex;
  width: 380px;
  height: 170px;
  overflow: hidden;
}
.picture-box div img {
  width: 145px;
  height: 145px;
  border-radius: 5px;
}
.title-box {
  margin-bottom: 5px;
}
.banner {
  transform: translateY(2px);
  width: 150px;
  margin-left: 5px;
}


</style>